package com.linkstec.stormmonitor.sender;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.linkstec.stormmonitor.common.sender.AlarmSender;
import com.linkstec.stormmonitor.util.DbUtil;

public class SMSSender extends AlarmSender{
	private static final Logger logger = LoggerFactory.getLogger(SMSSender.class);
	private final String insertSQL = "INSERT INTO MOT_MSG_SEND_FLOW(SEQ_NO,JOB_NAME,HAPPEN_TIME,MSG_CONTENT,TMPLT_TYPE,JOB_ID)"
			+ "VALUES(?,?,?,?,?,?)";
	private final String querySeqNoSQL = "SELECT  seq_MOT_MSG_SEND_FLOW.Nextval from dual";
	
	private final String sp_new_monitor = "call g_etl.pack_etl_monitor.sp_new_monitor(? ,? ,? ,? ,? ,?)";

	private int i = 1;
	@Override
	public void sendAlarm(List<String> contacts, List<String> alarmList) {
		
		Connection conn = DbUtil.getConnection();
		CallableStatement callableStatement = null;
		PreparedStatement ps = null;
		try {
			callableStatement = conn.prepareCall(sp_new_monitor);

		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		try {
			ps = conn.prepareStatement(insertSQL);
			for(String alarm : alarmList)
			{
				logger.info("错误大小：" + alarmList.size());
				logger.info(alarmList.toString());
				logger.info("发给他们：" + StringUtils.join(contacts,","));
				logger.info("注意！出错了！"+(i++)+"次");
				
				Long seqNo = null;
				PreparedStatement ps1 = conn.prepareStatement(querySeqNoSQL);
				ResultSet  rs = ps1.executeQuery();
				while(rs.next())
				{
					seqNo = rs.getLong(1);
				}
				rs.close();
				ps1.close();
				ps.setLong(1, seqNo);
				ps.setString(2, "SMOT任务");
				ps.setTimestamp(3, new java.sql.Timestamp(System.currentTimeMillis()));
				ps.setString(4, alarm.length() > 250 ? alarm.substring(0,250) : alarm);
				ps.setString(5,"9");
				ps.setString(6,seqNo + "");
				ps.addBatch();
				callableStatement.setString(1, alarm.substring(0,250));
				callableStatement.setString(2, "1");
				callableStatement.setString(3, "sms");
				callableStatement.setString(4, "1");
				callableStatement.setString(5, StringUtils.join(contacts, ","));
				callableStatement.setString(6, "");
				callableStatement.addBatch();
			}
			callableStatement.executeBatch();
			ps.executeBatch();
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally
		{
			if(callableStatement != null)
			{
				try {
					callableStatement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(ps != null)
			{
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}